﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyVoteMVC.Data;
using MyVoteMVC.Domain;
using MyVoteMVC.Common;
using MyVoteMVC.Common.Objects;
using MyVoteMVC.Data.Repositories;

namespace MyVoteMVC.Service
{
    public class VoteActivityService : IActivityService
    {
        private const string EmailAddress = "@gzdi.com";//接收方邮箱    
        IUnitOfWork unitOfWork;
        IRepository<VT_Activities> activitiesRepository;
        IRepository<VT_Tickets> ticketsRepository;
        IRepository<VT_Users> usersRepository;
        IRepository<VT_Lotteries> lotteriesRepository;

        public VoteActivityService()
        {
            unitOfWork = Factory.GetInstance<IUnitOfWork>();
            activitiesRepository = unitOfWork.GetRepository<VT_Activities>();
            ticketsRepository = unitOfWork.GetRepository<VT_Tickets>();
            usersRepository = unitOfWork.GetRepository<VT_Users>();
            lotteriesRepository = unitOfWork.GetRepository<VT_Lotteries>();
        }
        #region VoteActivityService Members

        //显示当前的投票活动情况（总共有多少人参与该投票活动、活动开始和结束时间）
        public IList<VT_Activities> GetActivitiesList(DateTime dtStartTime,DateTime dtEndTime)
        {
            IList<VT_Activities> v_Activities = activitiesRepository.GetMany(o => o.Activity_StartTime >= dtStartTime && o.Activity_EndTime <= dtEndTime).OrderBy(o=>o.Activity_No).ToList();
            return v_Activities;
        }

        public IList<VT_Activities> GetActivitiesList(DateTime dtTime)
        {
            IList<VT_Activities> v_Activities = activitiesRepository.GetMany(o => o.Activity_StartTime <= dtTime && o.Activity_EndTime >= dtTime).OrderBy(o => o.Activity_No).ToList();
            return v_Activities;
        }

        //进入活动后，可以显示投票活动的人气情况，即各个投票项的浏览人数或参与人数。
        public VT_Activities GetActivities(string activityID)
        {
            VT_Activities v_Activities = activitiesRepository.GetEntityById(activityID);
            //unitOfWork.BeginTransaction();
            //v_Activities.View_Count += 1;
            //activitiesRepository.Update(v_Activities);
            //unitOfWork.CommitTransaction();
            return v_Activities;
        }

        public VT_Activities GetActivities(string activityID, string activityPID)
        {
            VT_Activities v_Activities = activitiesRepository.GetMany(o => o.Activity_ID == activityID && o.Activity_PID == activityPID).FirstOrDefault();
            return v_Activities;
        }

        public IList<VT_Activities> GetHistoryActivitiesList(DateTime dtEndTime)
        {
            IList<VT_Activities> v_Activities = activitiesRepository.GetMany(o => o.Activity_EndTime <= dtEndTime).OrderBy(o=>o.Activity_No).ToList();
            return v_Activities;
        }

        //用户查看历史活动，普通用户不能查看二次活动，领导可以查看二次活动
        public IList<VT_Activities> GetHistoryActivitiesList(string userID)
        {
            int i = usersRepository.GetMany(o => o.User_IfLeaderValue == 1 && o.User_ID == userID).Count();
            // 大于0，显示所有的活动，小于0，不显示二次活动
            IList<VT_Activities> v_Activities = null;
            if (i > 0)
            {
                var v_Activitie = from activities in activitiesRepository.QueryableEntity()
                              where activities.Activity_EndTime < DateTime.Now
                              select activities;
                v_Activities = v_Activitie.OrderBy(o => o.Activity_No).ToList();
            }
            else
            {
                var v_Activitie = from activities in activitiesRepository.QueryableEntity()
                                  where activities.Activity_EndTime < DateTime.Now && (activities.ParentActivity.Activity_ID == null || activities.ParentActivity.Activity_ID == string.Empty)
                                  select activities;
                v_Activities = v_Activitie.OrderBy(o => o.Activity_No).ToList();
            }
            return v_Activities;
        }

        //用户查看当前活动，普通用户不能查看二次活动，领导可以查看二次活动
        public IList<VT_Activities> GetNowActivitiesList(string userID)
        {
            int i = usersRepository.GetMany(o => o.User_IfLeaderValue == 1 && o.User_ID == userID).Count();
            DateTime dt = DateTime.Now;
            // 大于0，显示所有的活动，小于0，不显示二次活动
            IList<VT_Activities> v_Activities = null;
            if (i > 0)
            {
                var v_Activitie = from activities in activitiesRepository.QueryableEntity()
                                  where activities.Activity_StartTime < dt && activities.Activity_EndTime > dt
                                  select activities;
                v_Activities = v_Activitie.OrderBy(o => o.Activity_No).ToList();
            }
            else
            {
                var v_Activitie = from activities in activitiesRepository.QueryableEntity()
                                  where activities.Activity_StartTime < dt && activities.Activity_EndTime > dt && (activities.ParentActivity.Activity_ID == null || activities.ParentActivity.Activity_ID == string.Empty)
                                  select activities;
                v_Activities = v_Activitie.OrderBy(o => o.Activity_No).ToList();
            }
            return v_Activities;
        }

        //查看用户参加过已结束的活动
        public IList<VT_Activities> GetUserHistoryActivitiesList(string userID,DateTime dtEndTime)
        {
            var v_Activitie = from activities in activitiesRepository.QueryableEntity()
                              join tickets in ticketsRepository.QueryableEntity() on activities.Activity_ID equals tickets.Activity_ID
                              where activities.Activity_EndTime < dtEndTime && tickets.User_ID == userID
                              select activities;
            IList<VT_Activities> v_Activities = v_Activitie.OrderBy(o=>o.Activity_No).ToList();
            return v_Activities;

            ////方式2       
            //var ticketsRepository = unitOfWork.GetRepository<VT_Tickets>();
            //var activitiesRepository = unitOfWork.GetRepository<VT_Activities>();
            //var activities1 = activitiesRepository.QueryableEntity();
            //var tickets1 = ticketsRepository.QueryableEntity().Where(o => o.User_ID == "11");
            //var ss = activities1.Join(tickets1, activity => activity.Activity_ID, ticket => ticket.Activity_ID, (activity, ticket) => activity).Where(o => o.Activity_EndTime < DateTime.Now);

        }

        //查看用户参加过没有结束的活动
        public IList<VT_Activities> GetUserNowActivitiesList(string userID, DateTime dtEndTime)
        {
            var v_Activitie = from activities in activitiesRepository.QueryableEntity()
                              join tickets in ticketsRepository.QueryableEntity() on activities.Activity_ID equals tickets.Activity_ID
                              where activities.Activity_EndTime > dtEndTime && tickets.User_ID == userID
                              select activities;
            IList<VT_Activities> v_Activities = v_Activitie.OrderBy(o=>o.Activity_No).ToList();

            return v_Activities;
        }

        //查看用户没有参加已结束的活动 
        public IList<VT_Activities> GetNotUserHistoryActivitiesList(string userID,DateTime dtEndTime)
        {
            var v_Activitie = from activities in activitiesRepository.QueryableEntity()
                              join tickets in ticketsRepository.QueryableEntity() on activities.Activity_ID equals tickets.Activity_ID
                              where activities.Activity_EndTime< dtEndTime && tickets.User_ID != userID
                              select activities;
            IList<VT_Activities> v_Activities = v_Activitie.OrderBy(o => o.Activity_No).ToList();

            return v_Activities;
 
        }

        //查看用户没有参加没有结束的活动
        public IList<VT_Activities> GetNotUserNowActivitiesList(string userID,DateTime dtEndTime)
        {
            var v_Activitie = from activities in activitiesRepository.QueryableEntity()
                              join tickets in ticketsRepository.QueryableEntity() on activities.Activity_ID equals tickets.Activity_ID
                              where activities.Activity_EndTime > dtEndTime && tickets.User_ID != userID
                              select activities;
            IList<VT_Activities> v_Activities = v_Activitie.OrderBy(o => o.Activity_No).ToList();

            return v_Activities;
        }

        public IList<VT_Users> GetUserJoinActivites(string activityID)
        {
            var v_UserList = from userses in usersRepository.QueryableEntity()
                              join tickets in ticketsRepository.QueryableEntity() on userses.User_ID equals tickets.User_ID
                              where tickets.Activity_ID == activityID
                              select userses;
            IList<VT_Users> vUserList = v_UserList.OrderBy(o => o.User_ID).ToList();

            return vUserList;
        }

        public IList<VT_Users> GetUserJoinActivitesNoLottery(string activityID)
        {
            var v_UserList = from userses in usersRepository.QueryableEntity()
                             join tickets in ticketsRepository.QueryableEntity() on userses.User_ID equals tickets.User_ID
                             where tickets.Activity_ID == activityID  
                             select userses;
            IList<VT_Users> vList = v_UserList.OrderBy(o => o.User_ID).ToList();
            IList<VT_Users> vUserList = v_UserList.OrderBy(o => o.User_ID).ToList();
 
            //检测，是否有中奖           
            foreach (VT_Users v_User in vList)
            {
                if (IsLottery(activityID, v_User.User_Email) == true || v_User.User_ID.Length < 4)
                {
                    vUserList.Remove(v_User);
                }
            }
            return vUserList;
        }

        public bool IsLottery(string activityID, string userEmail)
        {
            int i = lotteriesRepository.GetMany(o => o.Activity_ID == activityID && o.User_Email == userEmail && o.Lottery_TypeValue == 0).Count();
            if (i > 0)
                return true;
            else return false;
        }

        //添加活动
        public string AddActivity(string activityPID, string activityTitle, string activityContent, DateTime activityStartTime, DateTime activityEndTime, int activityIfShowUser, int activityIfReadAll, int activityIfMultiSubmit, string createdBy, byte[] activityImage)
        {
            
            string activityID = Guid.NewGuid().ToString();
            VT_Activities v_Activities = new VT_Activities();
            unitOfWork.BeginTransaction();
            v_Activities.Activity_ID = activityID;
            v_Activities.Activity_PID = activityPID;
            v_Activities.Activity_Title = activityTitle;  
            v_Activities.Activity_Content = activityContent;
            v_Activities.Activity_StartTime = activityStartTime;
            v_Activities.Activity_EndTime = activityEndTime;
            v_Activities.Activity_IfShowUser = activityIfShowUser;
            v_Activities.Activity_IfMultiSubmit = activityIfMultiSubmit;
            v_Activities.Activity_IfReadAll = activityIfReadAll;
            v_Activities.Created_By = createdBy;
            v_Activities.Created_Date = DateTime.Now;
            v_Activities.ActivityImage = new VT_ActivityImage();
            v_Activities.ActivityImage.Activity_ID = activityID;
            v_Activities.ActivityImage.Activity_Image = activityImage;
            v_Activities.View_Count = 0;

            string msx = (from activity in activitiesRepository.QueryableEntity()
                          select activity.Activity_No).Max();
            int iNum = 1;
            if (msx != null)
            {
                iNum = Convert.ToInt32(msx) + iNum;
            }
            msx = iNum.ToString();
            v_Activities.Activity_No = msx;

            activitiesRepository.Add(v_Activities);
            unitOfWork.CommitTransaction();
            return activityID;
        }

      
        public string AddActivity(string activityPID, string activityTitle, string activityContent, DateTime activityStartTime, DateTime activityEndTime, int activityIfShowUser, int activityIfReadAll, int activityIfMultiSubmit, string createdBy)
        {

            string activityID = Guid.NewGuid().ToString();
            VT_Activities v_Activities = new VT_Activities();
            unitOfWork.BeginTransaction();
            v_Activities.Activity_ID = activityID;
            v_Activities.Activity_PID = activityPID;
            v_Activities.Activity_Title = activityTitle;
            v_Activities.Activity_Content = activityContent;
            v_Activities.Activity_StartTime = activityStartTime;
            v_Activities.Activity_EndTime = activityEndTime;
            v_Activities.Activity_IfShowUser = activityIfShowUser;
            v_Activities.Activity_IfMultiSubmit = activityIfMultiSubmit;
            v_Activities.Activity_IfReadAll = activityIfReadAll;
            v_Activities.Created_By = createdBy;
            v_Activities.Created_Date = DateTime.Now;
            v_Activities.View_Count = 0;

            string msx = (from activity in activitiesRepository.QueryableEntity()
                          select activity.Activity_No).Max();
            int iNum = 1;
            if (msx != null)
            {
                iNum = Convert.ToInt32(msx) + iNum;
            }
            msx = iNum.ToString();
            v_Activities.Activity_No = msx;
            activitiesRepository.Add(v_Activities);
            unitOfWork.CommitTransaction();
            return activityID;
        }
        //删除活动
        public bool DeleteActivity(string activityID)
        {
            VT_Activities v_Activities = activitiesRepository.GetMany(o => o.Activity_ID == activityID).FirstOrDefault();
            if (v_Activities != null)
            {
                unitOfWork.BeginTransaction();
                activitiesRepository.Delete(v_Activities);
                unitOfWork.CommitTransaction();
                return true;
            }
            return false;
        }
        //修改活动
        public bool ModifyActivity(string activityID, string activityTitle, string activityContent, DateTime activityStartTime, DateTime activityEndTime, int activityIfShowUser, int activityIfReadAll, int activityIfMultiSubmit, string updateBy)
        {
            //updateBy = updateBy + EmailAddress;
            VT_Activities v_Activities = activitiesRepository.GetMany(o => o.Activity_ID == activityID).FirstOrDefault();
            if (v_Activities != null)
            {
                unitOfWork.BeginTransaction();
                v_Activities.Activity_Title = activityTitle;
                v_Activities.Activity_Content = activityContent;
                v_Activities.Activity_StartTime = activityStartTime;
                v_Activities.Activity_EndTime = activityEndTime;
                v_Activities.Activity_IfShowUser = activityIfShowUser;
                v_Activities.Activity_IfMultiSubmit = activityIfMultiSubmit;
                v_Activities.Activity_IfReadAll = activityIfReadAll;
                v_Activities.Last_Update_By = updateBy;
                v_Activities.Last_Update_Date = DateTime.Now;
                activitiesRepository.Update(v_Activities);
                unitOfWork.CommitTransaction();
                return true;
            }
            return false;


        }

        public bool AddActivityViewCount(string activityID)
        {
            VT_Activities v_Activities = activitiesRepository.GetEntityById(activityID);
            if (v_Activities != null)
            {
                unitOfWork.BeginTransaction();
                v_Activities.View_Count += 1;
                activitiesRepository.Update(v_Activities);
                unitOfWork.CommitTransaction();
                return true;
            }
            return false;
        }

        #endregion

        #region IDisposable Members
        private bool m_disposed;
        protected virtual void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                if (disposing)
                {
                    unitOfWork.Dispose();
                }

                // Release unmanaged resources

                m_disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~VoteActivityService()
        {
            Dispose(false);
        }
        #endregion


        public VT_Activities GetActivityByIdWhenAdmin(string Activity_ID)
        {
           return activitiesRepository.GetEntityById(Activity_ID);
        }

        public IList<VT_Activities> GetActivities()
        {
            return activitiesRepository.GetAll().OrderBy(o => o.Activity_No).ToList();
        }

        public bool CheckActivity(string Activity_ID)
        {
            return activitiesRepository.GetEntityById(Activity_ID).Activity_EndTime.Value < DateTime.Now;
        }
    }

}
